package com.bj58.heatmap.main;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.bj58.heatmap.db.HeatMapService;
import com.bj58.heatmap.model.HomeHeatMap;
import com.bj58.heatmap.util.DDateUtils;
import com.bj58.heatmap.util.IOUtils;
import com.bj58.heatmap.util.VelocityTools;
import com.bj58.wf.log.Log;
import com.bj58.wf.log.LogFactory;

/**
 * 新版M端热力图，根据张浩提供的tongji_tag标记匹配数据
 * @author zhaoxiang
 *
 */
public class ChangeStyle_M {
	
	private static Log log = LogFactory.getLog(ChangeStyle_M.class);
	
	private static HeatMapService service = new HeatMapService();
	
	private static String buttonBar = "";
	private static String colorBar = "\n<div align=\"center\">\n"
		+ "<table height=\"35\">\n" + "<tr>\n"
		+ "<td style=\"width:10%\" bgcolor=\"#e1e1e1\"></td>\n"+
		"<td><font color='red'><#1#</font></td>\n"+
		"<td style=\"width:10%\" bgcolor=\"#ffd985\"></td>\n"+
		"<td><font color='red'><#2#</font></td>\n"+
		"<td style=\"width:10%\" bgcolor=\"#ffa037\"></td>\n"+
		"<td><font color='red'><#3#</font></td>\n"+
		"<td style=\"width:10%\" bgcolor=\"#ff5f3d\"></td>\n"+
		"<td><font color='red'><#4#</font></td>\n"+
		 "<td style=\"width:10%\" bgcolor=\"#be0100\"></td>\n"
		+ "</tr>\n" + "</table>\n" + "</div>\n";
	
	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		Calendar calendar = Calendar.getInstance();
		String folder="";
		if(args==null||args.length==0){
			calendar.add(Calendar.DATE, -1);
			folder = new SimpleDateFormat("yyyyMMdd").format(calendar.getTime());
		}
		else{
			folder=args[0];
			calendar.set(Calendar.YEAR, Integer.parseInt(folder.substring(0, 4)));
			calendar.set(Calendar.MONTH, Integer.parseInt(folder.substring(4, 6))-1);
			calendar.set(Calendar.DATE, Integer.parseInt(folder.substring(6, 8)));
		}
		
		String stat_date = DDateUtils.strToStr(folder, "yyyyMMdd", "yyyy-MM-dd");
		long maxWait = 5*60*60*1000; //最多等5个小时
		while(maxWait > 0){
			log.info("begin check source table :"+stat_date);
			int count = service.countAll(stat_date);
			if(count > 0){
				log.info("source table has "+count+" recodes!");
				break;
			}
			log.info("source table is not ready then sleep for 10 minites!");
			maxWait -= 10*60*1000;
			Thread.sleep(10*60*1000);
		}
		File savePath = new File(WebCrawler.getHtmlPath() + folder); //源文件路径
		File savePath_new = new File(WebCrawler.getHtmlPath_new() + folder);	//目标文件路径
		if (!savePath_new.exists())
			savePath_new.mkdirs();
		File[] files = savePath.listFiles();
		log.info("begin changestyle :"+folder);
		for (File f : files) {
			if (f.isFile()) {
				String html = IOUtils.readFile(f);
				String t="pkg/index/index_common_homepage";
				html=html.replaceAll(t, "");
				String filename = f.getName();
				if (!filename.endsWith("_M.html")) //只处理M端的
					continue;
				html = changeStyle(html, calendar.getTime(),filename);
				IOUtils.saveFile(html, new File(savePath_new, filename));
			}
		}
		log.info("end changestyle :"+folder);
		System.exit(0);
	}


	/**
	 * 更改静态页面
	 * @param html
	 * @return
	 */
	public static String changeStyle(String html, Date date, String filename) {
		String strDate = DDateUtils.dateToStr(date, "yyyy-MM-dd");
		String folder = DDateUtils.dateToStr(date, "yyyyMMdd");
		String lastday = DDateUtils.varDate(strDate, "yyyy-MM-dd", Calendar.DATE, -1);
		
		String city=null;
		if (filename.endsWith("_M.html")) {
			city = filename.substring(0, filename.lastIndexOf("_"));
//			从mysql读数据
//			rowkey_prefix = date + "_M_" + city + "_";
			Map<String, HomeHeatMap> pv_uv_result = service.getCityData(strDate, city, "M");
			Map<String, HomeHeatMap> pv_uv_result_Y = service.getCityData(lastday, city, "M");
			//平均值
			long avgPV = getAVG(html, pv_uv_result);
			//切点
			long[] cutPoints = getCutPoint(avgPV);
			//根据链接匹配数据
			html = change_M(pv_uv_result,pv_uv_result_Y,folder,html,cutPoints);
			//添加颜色区间bar
			html = addColorBar_M(folder, city, html, cutPoints);
		} else {
//			city = filename.substring(0, filename.lastIndexOf("."));
//			Map<String, HomeHeatMap> pv_uv_result = service.getCityData(strDate, city, "PC");
//			Map<String, HomeHeatMap> pv_uv_result_Y = service.getCityData(lastday, city, "PC");
//			//平均值
//			long avgPV = getAVG(html, pv_uv_result);
//			//切点
//			long[] cutPoints = getCutPoint(avgPV);
//			//根据链接匹配数据
//			html = change_PC(pv_uv_result,pv_uv_result_Y,folder,html,cutPoints);
//			//添加颜色区间bar
//			html = addColorBar_PC(folder, city, html, cutPoints);
		}
		return html;
	}

	/**
	 * 添加颜色区间bar
	 * @param date
	 * @param city
	 * @param html
	 * @param maxUV
	 * @return
	 */
	public static String addColorBar_PC(String date,String city,String html,long[] cutPoints){
		//添加label，指向该城市M端的链接
		buttonBar = "<div align=\"center\">\n<br/>\n<button type=\"button\">\n"
			+ " <a href=\"/heatmap/getPage?selectpvtype=m&selectdate="+date+"&selectedcityname="+city+"\" target=\"_self\">切换到m端</a>\n" + "</button>\n</div>";
		String replacedColorBar = colorBar.replace("#1#", String.valueOf(cutPoints[0]));
		replacedColorBar = replacedColorBar.replace("#2#", String.valueOf(cutPoints[1]));
		replacedColorBar = replacedColorBar.replace("#3#", String.valueOf(cutPoints[2]));
		replacedColorBar = replacedColorBar.replace("#4#", String.valueOf(cutPoints[3]));
		html=html.replaceFirst("<div\\s{1,}(.*?)id=('|\")header\\2(.*?)>", "<div $1id=\"header\"$3>" + replacedColorBar+buttonBar);
		return html;
	}
	
	public static String addColorBar_M(String date,String city,String html,long[] cutPoints){
		//添加button，指向该城市 PC 端的链接
		buttonBar = "<div align=\"center\">\n<br/>\n<button type=\"button\">\n"
			+ " <a href=\"/heatmap/getPage?selectpvtype=pc&selectdate="+date+"&selectedcityname="+city+"\" target=\"_self\">切换到pc端</a>\n" + "</button>\n</div>";
		String replacedColorBar = colorBar.replace("#1#", String.valueOf(cutPoints[0]));
		replacedColorBar = replacedColorBar.replace("#2#", String.valueOf(cutPoints[1]));
		replacedColorBar = replacedColorBar.replace("#3#", String.valueOf(cutPoints[2]));
		replacedColorBar = replacedColorBar.replace("#4#", String.valueOf(cutPoints[3]));
		html=html.replaceFirst("(<body.*?>)","$1" + replacedColorBar+buttonBar);
		return html;
	}
	
	public static String change_PC(Map<String, HomeHeatMap> pv_uv_result,Map<String, HomeHeatMap> pv_uv_result_Y, String date, String html,long[] cutPoints){
		StringBuffer sb = new StringBuffer();
		try {
			Pattern p = Pattern.compile("<a(.*?)\\s*>", Pattern.DOTALL);
			Pattern href = Pattern.compile("tongji_tag=(['\"])(.*?)\\1");
			Matcher m = p.matcher(html);
			while (m.find()) {
				String a = m.group(1);
				Matcher mat = href.matcher(a);
				if (!mat.find()) {
					String x= m.group(0);
					m.appendReplacement(sb, x);
					continue;
				}
				String toURL = mat.group(2).trim();
				HomeHeatMap pv_uv_data = pv_uv_result.get(toURL.trim());
				HomeHeatMap pv_uv_data_Y=pv_uv_result_Y.get(toURL.trim());
				int pvCount = 0, uvCount = 0,lastpv=0,lastuv=0;
				if (pv_uv_data != null) {
					pvCount = pv_uv_data.getClick_pv();
					uvCount = pv_uv_data.getClick_uv();
				}
				if(pv_uv_data_Y!=null){
					lastpv = pv_uv_data_Y.getClick_pv();
					lastuv = pv_uv_data_Y.getClick_uv();
				}
				if (pvCount < cutPoints[0])
					m.appendReplacement(sb,changeColor(a, "#e1e1e1", pvCount, uvCount,lastpv,lastuv));
				else if (pvCount < cutPoints[1])
					m.appendReplacement(sb,
							changeColor(a, "#ffd985", pvCount, uvCount,lastpv,lastuv));
				else if (pvCount < cutPoints[2])
					m.appendReplacement(sb,
							changeColor(a, "#ffa037", pvCount, uvCount,lastpv,lastuv));
				else if (pvCount < cutPoints[3])
					m.appendReplacement(sb,
							changeColor(a, "#ff5f3d", pvCount, uvCount,lastpv,lastuv));
				else
					m.appendReplacement(sb,
							changeColor(a, "#be0100", pvCount, uvCount,lastpv,lastuv));
			}
			m.appendTail(sb);
		} catch (Exception e) {
			e.printStackTrace();
			return html;
		}
		return changeImgPath(sb.toString(),date);
	}
	
	public static String change_M(Map<String, HomeHeatMap> pv_uv_result, Map<String, HomeHeatMap> pv_uv_result_Y,String date, String html,long[] cutPoints){
		StringBuffer sb = new StringBuffer();
		try {
			Pattern p = Pattern.compile("<a(.*?)\\s*>", Pattern.DOTALL);
			Pattern href = Pattern.compile("tongji_tag=(['\"])(.*?)\\1");
			Matcher m = p.matcher(html);
			while (m.find()) {
				String a = m.group(1);
				Matcher mat = href.matcher(a);
				if (!mat.find()) {
					String x= m.group(0);
					m.appendReplacement(sb, x);
					continue;
				}
				String toURL = mat.group(2).trim();
				HomeHeatMap pv_uv_data = pv_uv_result.get(toURL.trim());
				HomeHeatMap pv_uv_data_Y=pv_uv_result_Y.get(toURL.trim());
				int pvCount = 0;
				if (pv_uv_data == null) {
					pv_uv_data = new HomeHeatMap();
				}
				if(pv_uv_data_Y == null){
					pv_uv_data_Y = new HomeHeatMap();
				}
				pvCount = pv_uv_data.getClick_pv();
				if (pvCount < cutPoints[0])
					m.appendReplacement(sb,changeColor(a, "#e1e1e1", pv_uv_data,pv_uv_data_Y));
				else if (pvCount < cutPoints[1])
					m.appendReplacement(sb,
							changeColor(a, "#ffd985", pv_uv_data,pv_uv_data_Y));
				else if (pvCount < cutPoints[2])
					m.appendReplacement(sb,
							changeColor(a, "#ffa037", pv_uv_data,pv_uv_data_Y));
				else if (pvCount < cutPoints[3])
					m.appendReplacement(sb,
							changeColor(a, "#ff5f3d", pv_uv_data,pv_uv_data_Y));
				else
					m.appendReplacement(sb,
							changeColor(a, "#be0100", pv_uv_data,pv_uv_data_Y));
			}
			m.appendTail(sb);
		} catch (Exception e) {
			e.printStackTrace();
			return html;
		}
		return changeImgPath_M(sb.toString(),date);
	}
	
	private static String changeColor(String a, String color, HomeHeatMap pv_uv_data, HomeHeatMap pv_uv_data_Y) {
		
		String startStr = "<a title=\"点击量&nbsp;&nbsp;&nbsp;:" + pv_uv_data.getClick_pv() 
		+"&nbsp;&nbsp;&nbsp;环比:&nbsp;&nbsp;&nbsp;" + VelocityTools.compRate2(pv_uv_data.getClick_pv(),pv_uv_data_Y.getClick_pv())
		+ "&#13;点击人数:"  + pv_uv_data.getClick_uv() 
		+ "&nbsp;&nbsp;&nbsp;环比:&nbsp;&nbsp;&nbsp;" + VelocityTools.compRate2(pv_uv_data.getClick_uv(),pv_uv_data_Y.getClick_uv())
		+ "&#13;后续转化：&#13;详情页PV:" + pv_uv_data.getAll_vppv() 
		+ "&nbsp;&nbsp;&nbsp;环比:&nbsp;&nbsp;&nbsp;" + VelocityTools.compRate2(pv_uv_data.getAll_vppv(),pv_uv_data_Y.getAll_vppv())
		+ "&#13;详情页UV:" + pv_uv_data.getAll_vpuv() 
		+ "&nbsp;&nbsp;&nbsp;环比:&nbsp;&nbsp;&nbsp;" + VelocityTools.compRate2(pv_uv_data.getAll_vpuv(),pv_uv_data_Y.getAll_vpuv())
		+ "\"";
		String replaced;
		int i = a.indexOf("style=\"");
		if (i > 0) {
			replaced = startStr + a.substring(0, i)
					+ "style=\"background-color:" + color + "; "
					+ a.substring(i + 7) + ">";
		} else{
			replaced = startStr + a + " style=\"background-color:" + color + "\">";
			
		}
		// System.out.println(replaced);
		return replaced;
	}

	/**
	 * 更改背景色
	 * 
	 * @param a
	 * @param color
	 * @param pv
	 * @param uv
	 * @return
	 */
	public static String changeColor(String a, String color, int pv, int uv,int lastpv,int lastuv) {
		String startStr = "<a title=\"点击量:" + pv + "&#13;点击人数:" + uv + "&#13;前一天：&#13;点击量:"+ lastpv + "&#13;点击人数:" + lastuv + "\"";
		String replaced;
		int i = a.indexOf("style=\"");
		if (i > 0) {
			replaced = startStr + a.substring(0, i)
					+ "style=\"background-color:" + color + "; "
					+ a.substring(i + 7) + ">";
		} else
			replaced = startStr + a + " style=\"background-color:" + color
					+ "\">";
		// System.out.println(replaced);
		return replaced;
	}

	/**
	 * 更改图片路径
	 * 
	 * @param html
	 * @param date
	 * @return
	 */
	public static String changeImgPath(String html, String date) {
		StringBuffer sb = new StringBuffer();
		ArrayList<String> srcList = new ArrayList<String>();
		String srcReg = "http://([^<>'+()]*?)\\.(js|css|jpeg|jpg|png|gif|bmp|swf)";
		try {
			Pattern p = Pattern.compile(srcReg);
			Matcher m = p.matcher(html);
			while (m.find()) {
				String src = m.group();
				srcList.add(src);
				int i = src.indexOf("?");
				if (i != -1)
					src = src.substring(0, i);
				m.appendReplacement(sb,
						"/heatmap/" + date + "/"
								+ src.substring(src.lastIndexOf("/") + 1));
			}
			m.appendTail(sb);
		} catch (Exception e) {
			e.printStackTrace();
			return html;
		}
		return sb.toString();
	}

	/**
	 * 更改图片路径
	 * 
	 * @param html
	 * @param date
	 * @return
	 */
	public static String changeImgPath_M(String html, String date) {
		StringBuffer sb = new StringBuffer();
		ArrayList<String> srcList = new ArrayList<String>();
		String srcReg = "http://([^<>'+()]*?)\\.(js|css|jpeg|jpg|png|gif|bmp|swf)";
		try {
			Pattern p = Pattern.compile(srcReg);
			Matcher m = p.matcher(html);
			while (m.find()) {
				String src = m.group();
				srcList.add(src);
				int i = src.indexOf("?");
				if (i != -1)
					src = src.substring(0, i);
				m.appendReplacement(sb,
						"/heatmap/" + date + "/M_"
								+ src.substring(src.lastIndexOf("/") + 1));
			}
			m.appendTail(sb);
		} catch (Exception e) {
			e.printStackTrace();
			return html;
		}
		return sb.toString();
	}
	
	public static long getAVG(String html, Map<String, HomeHeatMap> pv_uv_result){
		long totalPV = 0;
		for(HomeHeatMap vo : pv_uv_result.values()){
			totalPV += vo.getClick_pv();
		}
		
		if(pv_uv_result.values().size()  > 0)
			return totalPV/pv_uv_result.values().size();
		return 1;
	}
	
	public static long[] getCutPoint(long avg){
		long p1 = (long)(avg*0.6);
		long p2 = (long)(avg*1.8);
		long p3 = (long)(avg*3);
		long p4 = (long)(avg*6);
		if(avg >= 167){
			return new long[]{p1/100*100,p2/100*100,p3/100*100,p4/100*100};
		}else if(avg <=17){
			return new long[]{p1,p2,p3,p4};
		}else{
			return new long[]{p1/10*10,p2/10*10,p3/10*10,p4/10*10};
		}
	}
}
